﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using HousingInfo.Library;

namespace WebHousingInfo
{
    public partial class QuanLyCaNhan : System.Web.UI.Page
    {
        private static string mode = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["UserName"] == null)
                    Response.Redirect("DangNhap.aspx");
                string sesion = (String)Session["managernews"];                
                mode = Request.QueryString["xemtin"];
                BindGrid();
                GridView1.Columns[1].Visible = false;
                if (sesion == "thanhcong")
                {
                    Session["managernews"] = null;
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success", "alert('Cập nhật thành công !')", true);
                }
                if (mode == "daluu" || mode =="hethan" || mode == "choduyet")
                {
                    btnketthuc.Visible = false;
                }
            }
        }

        public void GettotalNewsHouse()
        {
            lbltraphi.Text = "[" + NewsHouseBOList.GetType_NewsHousesBOList_ByUserName(Session["UserName"].ToString().ToString(), false, true, false, false, false, false).Count.ToString() + "]";
            lblchoduyet.Text = "[" + NewsHouseBOList.GetType_NewsHousesBOList_ByUserName(Session["UserName"].ToString(), false, false, false, true, false, false).Count.ToString() + "]";
            lbldangdang.Text = "[" + NewsHouseBOList.GetType_NewsHousesBOList_ByUserName(Session["UserName"].ToString(), false, false, true, false, false, false).Count.ToString() + "]";
            lbldaluu.Text = "[" + NewsHouseBOList.GetType_NewsHousesBOList_ByUserName(Session["UserName"].ToString(), false, false, false, false, true, false).Count.ToString() + "]";
            lblhethan.Text = "[" + NewsHouseBOList.GetType_NewsHousesBOList_ByUserName(Session["UserName"].ToString(), false, false, false, false, false, true).Count.ToString() + "]";
            lbltatca.Text = "[" + NewsHouseBOList.GetType_NewsHousesBOList_ByUserName(Session["UserName"].ToString(), true, false, false, false, false, false).Count.ToString() + "]";
        }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            Response.Redirect("DangTin.aspx?id=" + GridView1.SelectedRow.Cells[3].Text);
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    var UrlImage = (Label)e.Row.Cells[7].FindControl("lblimage");
                    //string imageString = "img/noimage.gif";
                    string imageString;
                    if (UrlImage.Text != "")
                    {
                        var arrayimage = UrlImage.Text.Split('/');
                        var pathFileImage = Server.MapPath("TotalUpload/ImagesTotal/" + arrayimage[0]);
                        if (File.Exists(pathFileImage))
                        {
                            imageString = "TotalUpload/ImagesTotal/" + arrayimage[0];
                        }
                        else imageString = "TotalUpload/ImagesTotal/noimage.gif";
                    }
                    else imageString = "TotalUpload/ImagesTotal/noimage.gif";

                    var LinkButtonTitle = (LinkButton)e.Row.Cells[4].FindControl("lbttitle");
                    var labelsurfaceArea = (Label)e.Row.Cells[7].FindControl("lbldientich");
                    var labelsurfaceAreaHeight = (Label)e.Row.Cells[7].FindControl("lbldientichdai");
                    string dientich = "";
                    if (labelsurfaceArea.Text == "-1")
                    {
                        dientich = "Chưa có";
                    }
                    else if (labelsurfaceArea.Text == labelsurfaceAreaHeight.Text)
                    {
                        dientich = labelsurfaceArea.Text + " " + "m<sup>2</sup>";
                    }
                    else
                    {
                        dientich = labelsurfaceArea.Text + " x " + labelsurfaceAreaHeight.Text + " (m x m) ";
                    }
                    var labelPrice = (Label)e.Row.Cells[7].FindControl("lblgia");
                    var labelLoaitien = (Label)e.Row.Cells[7].FindControl("lblloaitien");
                    var cbsupm = (CheckBox)e.Row.Cells[7].FindControl("cbSup");
                    string issupm = "";
                    if (cbsupm.Checked == true) issupm = "/m<sup>2</sup>";
                    string price_loaitien_sup = "";
                    if (Convert.ToInt32(labelPrice.Text) == -1)
                    {
                        price_loaitien_sup = "Chưa có giá";
                    }
                    else price_loaitien_sup = labelPrice.Text + "  " + labelLoaitien.Text + "  " + issupm;

                    var labelAreaDetail = (Label)e.Row.Cells[7].FindControl("lblvitri");
                    var hiddenFielContent = (Label)e.Row.Cells[7].FindControl("lblmota");
                    var hiddenFielContentShort = hiddenFielContent.Text.Length > 20
                                                     ? hiddenFielContent.Text.Substring(0, 20) + "..."
                                                     : hiddenFielContent.Text;
                    string strHtml = "<table><tr><td rowspan=4 class=\"tootipadmin\"><img width=\"130\" height=\"130\"  src=\"" + imageString + "\"/></td>";
                    strHtml += "<td style=\"padding-right:5px;\"><b>Diện tích:</b></td><td>" + dientich + "</td></tr>";
                    strHtml += "<tr><td><b>Gía:</b></td><td style=\"color:red;\">" + price_loaitien_sup + "</td></tr>";
                    strHtml += "<tr><td><b>Vị trí:</b></td><td>" + labelAreaDetail.Text + "</td></tr>";
                    strHtml += "<tr><td><b>Hướng:</b></td><td>" + hiddenFielContentShort + "</td></tr></table>";

                    LinkButtonTitle.Attributes.Add("onMouseover", "ddrivetip('" + strHtml + "', 360);");
                    LinkButtonTitle.Attributes.Add("onMouseout", "hideddrivetip();");
                    LinkButtonTitle.Attributes.Add("onMouseover", "ddrivetip('" + strHtml + "', 360);");
                    LinkButtonTitle.Attributes.Add("onMouseout", "hideddrivetip();");

                    string strScript = "SelectDeSelectHeader(" + ((CheckBox)e.Row.Cells[0].FindControl("chkSelect")).ClientID + ");";
                    ((CheckBox)e.Row.Cells[0].FindControl("chkSelect")).Attributes.Add("onclick", strScript);
                }
            }
            catch { }
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Xem2")
            {
                GridViewRow selectrow = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
                string Title = ((LinkButton)(((Control)e.CommandSource).Parent.Parent).FindControl("lbttitle")).Text;
                Response.Redirect("TinNhaDatChiTiet.aspx?id=" + selectrow.Cells[3].Text);
            }
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            this.BindGrid();
        }

        public void BindGrid()
        {
            GettotalNewsHouse();
            if (mode == "traphi")
            {
                lbltin.Text = "TIN TRẢ PHÍ";
                GridView1.DataSource = NewsHouseBOList.GetType_NewsHousesBOList_ByUserName(Session["UserName"].ToString(), false, true, false, false, false, false);
                GridView1.DataBind();
            }
            else if (mode == "choduyet")
            {
                lbltin.Text = "TIN CHỜ DUYỆT";
                GridView1.DataSource = NewsHouseBOList.GetType_NewsHousesBOList_ByUserName(Session["UserName"].ToString(), false, false, false, true, false, false);
                GridView1.DataBind();
            }
            else if (mode == "dangdang")
            {
                lbltin.Text = "TIN ĐANG ĐĂNG";
                GridView1.DataSource = NewsHouseBOList.GetType_NewsHousesBOList_ByUserName(Session["UserName"].ToString(), false, false, true, false, false, false);
                GridView1.DataBind();
            }
            else if (mode == "daluu")
            {
                lbltin.Text = "TIN ĐÃ LƯU";
                GridView1.DataSource = NewsHouseBOList.GetType_NewsHousesBOList_ByUserName(Session["UserName"].ToString(), false, false, false, false, true, false);
                GridView1.DataBind();
            }
            else if (mode == "hethan")
            {
                lbltin.Text = "TIN HẾT HẠN";
                GridView1.DataSource = NewsHouseBOList.GetType_NewsHousesBOList_ByUserName(Session["UserName"].ToString().ToString(), false, false, false, false, false, true);
                GridView1.DataBind();
            }
            else
            {
                lbltin.Text = "TẤT CẢ TIN";
                GridView1.DataSource = NewsHouseBOList.GetType_NewsHousesBOList_ByUserName(Session["UserName"].ToString(), true, false, false, false, false, false);
                GridView1.DataBind();
            }
        }

        protected void btnxoa_Click(object sender, EventArgs e)
        {
            bool test = false;
            NewsHouseBO newshBO;
            foreach (GridViewRow gvRow in GridView1.Rows)
            {
                CheckBox chkSel = (CheckBox)gvRow.FindControl("chkSelect");
                if (chkSel.Checked == true)
                {
                    try
                    {
                        test = true;
                        int newsid = Convert.ToInt32(gvRow.Cells[3].Text);
                        //daluu
                        if (mode == "daluu")
                        {
                            NewsSaveBO.DeleteNewsSaveBO(NewsSaveBO.LayIdNewsSave_ByNewsHouseAndUserName(newsid, Session["UserName"].ToString()));
                        }
                        else
                        {
                            NewsHouseBOList.Delete_ByKey(newsid);
                            newshBO = NewsHouseBO.GetNewsHouseBO(newsid);
                            if (newshBO.UrlImage != "")
                            {
                                var array_listImage = newshBO.UrlImage.Split('/');
                                foreach (var detail in array_listImage)
                                {
                                    deleteExitsImage(detail);
                                }
                            }
                            NewsHouseBO.DeleteNewsHouseBO(newsid);
                        }
                    }
                    catch
                    {
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success", "alert('Xoá thất bại!!!')", true);
                        BindGrid();
                        return;
                    }
                }
            }
            if (test == false)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success", "alert('Chưa chọn tin cần xóa!!!')", true);
                return;
            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success", "alert('Xoá thành công!!!')", true);
                BindGrid();
            }  
        }

        private void deleteExitsImage(string filedelete)
        {
            try
            {
                var pathFileImage = Server.MapPath("TotalUpload/ImagesTotal/" + filedelete);
                FileInfo fileInfo;
                if (File.Exists(pathFileImage))
                {
                    fileInfo = new FileInfo(pathFileImage);
                    fileInfo.Delete();
                }
            }
            catch
            {
            }
        }
        public bool checkurlimage(string imagestring)
        {
            var pathFileImage = Server.MapPath("TotalUpload/UserAvatar/" + imagestring);
            if (File.Exists(pathFileImage))
            {
                return true;
            }
            else return false;
        }
        protected void btnketthuc_Click(object sender, EventArgs e)
        {
            bool test = false;
            NewsHouseBO newshBO;
            foreach (GridViewRow gvRow in GridView1.Rows)
            {
                CheckBox chkSel = (CheckBox)gvRow.FindControl("chkSelect");
                if (chkSel.Checked == true)
                {
                    try
                    {
                        test = true;
                        int newsid = Convert.ToInt32(gvRow.Cells[3].Text);
                        newshBO = NewsHouseBO.GetNewsHouseBO(newsid);
                        newshBO.IsActive = false;
                        newshBO.Save();
                    }
                    catch
                    {
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success", "alert('Kết thúc đăng tin thất bại!!!')", true);
                        BindGrid();
                        return;
                    }
                }
            }
            if (test == false)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success", "alert('Chưa chọn tin !')", true);
                return;
            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success", "alert('Đã kết thúc đăng tin của các tin đã chọn!!!')", true);
                BindGrid();
            }
        }
    }
}
